package com.ly.crawl.impl;


import com.ly.crawl.DataDao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SimpleDataDao implements DataDao<Map<String, Object>> {
    private static final String QUERY_COLUMN_LENGTH_SQL = "SELECT\n" +
            "	a.COLUMN_NAME,a.CHARACTER_MAXIMUM_LENGTH\n" +
            "FROM\n" +
            "	`information_schema`.`COLUMNS` a\n" +
            "WHERE\n" +
            "	`TABLE_NAME` = ?\n" +
            "AND `TABLE_SCHEMA` = ?";
    private static final String DBNAME = "test";

// TODO    static {
//         DBHelper.init("mysql.test");
//    }

    private final String table;
    private Map<String, Integer> columnLengthMap = new HashMap<>();

    public SimpleDataDao(String table) {
        this(table, true);
    }

    public SimpleDataDao(String table, boolean isRecreate) {
        this.table = table;
        initColumnLength();
        if (isRecreate && ! columnLengthMap.isEmpty()) {
            String sql = "drop table " + table;
            // TODO DBHelper.update(sql);
            columnLengthMap.clear();
        }
    }

    private void initColumnLength() {
        List<Map<String, Object>> list = null;// DBHelper.selectListMap(QUERY_COLUMN_LENGTH_SQL, table, DBNAME);
        for (Map<String, Object> row : list) {
            if (row.get("CHARACTER_MAXIMUM_LENGTH") != null) {
                columnLengthMap.put((String) row.get("COLUMN_NAME"), Integer.valueOf(row.get("CHARACTER_MAXIMUM_LENGTH") + ""));
            } else if (row.get("CHARACTER_MAXIMUM_LENGTH".toLowerCase()) != null) {
                columnLengthMap.put((String) row.get("COLUMN_NAME".toLowerCase()),
                        Integer.valueOf(row.get("CHARACTER_MAXIMUM_LENGTH".toLowerCase()) + ""));
            }
        }
    }

    private void createTable(Map<String, Object> data) {
        if (columnLengthMap.isEmpty()) {
            String sql = "create table " + table + "(" +
                    "`id` int(11) NOT NULL auto_increment";
            for (Map.Entry<String, Object> nc : data.entrySet()) {
                if ("id".equals(nc.getKey()) == false) {
                    sql += ",`" + nc.getKey() + "` varchar(20) default NULL";
                }
            }
            sql += ",PRIMARY KEY  (`id`))";
            // TODO DBHelper.update(sql);
            initColumnLength();
        }
    }

    private boolean correctColumnLength(Map<String, Object> data) {
        for (Map.Entry<String, Object> e : data.entrySet()) {
            if (!(e.getValue() instanceof String)) {
                continue;
            }
            String svalue = (String) e.getValue();
            if (svalue.length() >= 21215) {
                System.out.println("=================== 数据太大 : " + e.getKey() + " ==== 你看吧 ==============");
                System.out.println(data);
                System.out.println("=================== 数据太大 : " + e.getKey() + " ==== 放弃了 ==============");
                return false;
            }
            if (columnLengthMap.get(e.getKey()) != null && columnLengthMap.get(e.getKey()) < svalue.length()) {
                String sql = "ALTER TABLE " + table + " MODIFY COLUMN " + e.getKey() + " VARCHAR(" + svalue.length() + ")";
                try {
                    // TODO DBHelper.update(sql);
                    columnLengthMap.put(e.getKey(), svalue.length());
                } catch (RuntimeException e1) {
                    e1.printStackTrace();
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void save(Map<String, Object> data) {
// TODO       DBHelper.execute(c -> {
//            createTable(data);
//            if (correctColumnLength(data)) {
//                String update = "update %s set %s where id = %s";
//                String insert = "insert into %s ( %s ) values ( %s )";
//                String cols = data.containsKey("id") ? "" : "id";
//                String vals = data.containsKey("id") ? "" : "default";
//                String sets = "";
//                for (Map.Entry<String, Object> en : data.entrySet()) {
//                    cols += cols.isEmpty() ? "" : ",";
//                    vals += vals.isEmpty() ? "" : ",";
//                    sets += sets.isEmpty() ? "" : ",";
//                    cols += en.getKey();
//                    vals += "?";
//                    sets += en.getKey() + "=?";
//                }
//                insert = String.format(insert, table, cols, vals);
//                update = String.format(update, table, sets, data.get("id"));
//                 if (DBHelper.update(update, data.values().toArray(new Object[data.size()])) == 0) {
//                    DBHelper.update(insert, data.values().toArray(new Object[data.size()]));
//                }
//            }
//            return null;
//        });

    }

}
